package com.dayaokeji.rhythmschoolstudent.client.mine.account;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewCompat;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.dayaokeji.rhythmschoolstudent.BuildConfig;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.callback.SoftKeyBoardListener;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.Constant;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.main.MainActivity;
import com.dayaokeji.rhythmschoolstudent.client.mine.account.bean.RemoteHostPicker;
import com.dayaokeji.rhythmschoolstudent.databases.dao.UserInfoDao;
import com.dayaokeji.rhythmschoolstudent.event.UpdateCourseEvent;
import com.dayaokeji.rhythmschoolstudent.utils.AndroidUtils;
import com.dayaokeji.rhythmschoolstudent.utils.DialogUtils;
import com.dayaokeji.rhythmschoolstudent.utils.InputUtils;
import com.dayaokeji.rhythmschoolstudent.utils.JPushAliasUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ObjectUtils;
import com.dayaokeji.rhythmschoolstudent.utils.PrefUtils;
import com.dayaokeji.rhythmschoolstudent.utils.RemoteHostUtil;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.SystemApi;
import com.dayaokeji.server_api.api.UserApi;
import com.dayaokeji.server_api.domain.RemoteHost;
import com.dayaokeji.server_api.domain.UserInfo;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import retrofit2.Call;

/**
 * 工号学号登录
 */
public class StudentIdLoginActivity extends BaseActivity {

    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_choose_school_name)
    TextView tvChooseSchoolName;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.ll_from)
    LinearLayout llFrom;
    @BindView(R.id.tv_login_title)
    TextView tvLoginTitle;
    @BindView(R.id.tv_user_policy)
    TextView tvUserPolicy;

    private Call<ServerResponse<UserInfo>> loginCall;
    private static final SystemApi systemApi  = ApiUtils.getApi(SystemApi.class);
    private Call<ServerResponse<List<RemoteHost>>> remoteHostCall;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTranslucentStatusEnabled(true);
        setContentView(R.layout.activity_student_id_login);
        userPolicy();
        updateRemoteHost();
        init();
    }

    private void init() {
        RemoteHostPicker currentRemoteHost = RemoteHostUtil.getCurrentRemoteHost();
        if (currentRemoteHost != null) {
            tvChooseSchoolName.setText(currentRemoteHost.getName());
            tvChooseSchoolName.setTag(currentRemoteHost.getId());
            RetrofitUrlManager.getInstance().setGlobalDomain(currentRemoteHost.getHost());
        }
        String lastJobNumber = PrefUtils.getLastJobNumber();
        if (!TextUtils.isEmpty(lastJobNumber)) {
            etName.setText(lastJobNumber);
        }
        String lastPassword = PrefUtils.getLastPassword();
        etPassword.setText(lastPassword);
        setOnListener();
    }

    private void userPolicy() {
        final SpannableString spannableString = new SpannableString("登录即代表阅读并同意隐私政策");
        spannableString.setSpan(new ForegroundColorSpan(Color.rgb(1, 121, 251)), 10, spannableString.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                UserPrivacyPolicyActivity.Companion.navigation(StudentIdLoginActivity.this);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.rgb(1, 121, 251));
            }
        };
        spannableString.setSpan(clickableSpan, 10, spannableString.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
        if (tvUserPolicy != null) {
            tvUserPolicy.setText(spannableString);
            tvUserPolicy.setMovementMethod(LinkMovementMethod.getInstance());
        }
    }

    @OnClick({
            R.id.btn_login,
            R.id.tv_forget_password,
            R.id.ll_choose_school,
            R.id.tv_register
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                login();
                break;
            case R.id.tv_forget_password:
                goForgetPassword();
                break;
            case R.id.ll_choose_school:
                requestRemoteHost();
                break;
            case R.id.tv_register:
                goRegister();
                break;
        }
    }


    private void setOnListener() {
        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                ViewCompat.animate(tvLoginTitle).translationY(AndroidUtils.dp2px(-200)).setDuration(700).start();
                ViewCompat.animate(llFrom).translationY(AndroidUtils.dp2px(-150)).setDuration(700).start();
            }

            @Override
            public void keyBoardHide(int height) {
                ViewCompat.animate(tvLoginTitle).translationY(1).setDuration(700).start();
                ViewCompat.animate(llFrom).translationY(1).setDuration(700).start();
            }
        });
    }

    /**
     * 忘记密码
     */
    private void goRegister() {
        RemoteHostPicker currentRemoteHost = RemoteHostUtil.getCurrentRemoteHost();
        if (tvChooseSchoolName.getTag() == null || currentRemoteHost == null) {
            ToastUtils.info("请先选择学校");
            return;
        }
        boolean allowregister = currentRemoteHost.isAllowregister();
        if (allowregister) {
            Intent intent = new Intent(this, VerifyPhoneNumberActivity.class);
            intent.putExtra(VerifyPhoneNumberActivity.EXTRA_VERIFY_TYPE, Constant.MOBILE_VERIFY_TYPE_REGISTER);
            startActivity(intent);
        }else{
            DialogUtils.getAlertDialog(StudentIdLoginActivity.this, "注册提示", "系统已录入"+currentRemoteHost.getName()+"学校的人员信息，请您使用教务管理系统的账号密码登录。若无法登陆，请联系学校管理员", (dialog, which) -> dialog.dismiss());
        }

    }


    /**
     * 忘记密码
     */
    private void goForgetPassword() {
        Intent intent = new Intent(this, VerifyPhoneNumberActivity.class);
        intent.putExtra(VerifyPhoneNumberActivity.EXTRA_VERIFY_TYPE, Constant.MOBILE_VERIFY_TYPE_FORGET_PASSWORD);
        startActivity(intent);
    }

    /**
     * 请求远程域名地址
     */
    private void requestRemoteHost() {
        remoteHostCall = systemApi.remoteHost();
        remoteHostCall.enqueue(new ServerCallback<List<RemoteHost>>(this,"正在获取学校数据...") {
            @Override
            public void onResponse(boolean success, ServerResponse<List<RemoteHost>> response) {
                if (success) {
                    if (!StudentIdLoginActivity.this.isFinishing()) {
                        List<RemoteHostPicker> remoteHostPickers = new ArrayList<>();
                        final List<RemoteHost> body = response.getBody();
                        for (RemoteHost remoteHost : body) {
                            final RemoteHostPicker picker = new RemoteHostPicker();
                            picker.setHost(remoteHost.getHost());
                            picker.setName(remoteHost.getName());
                            picker.setId(remoteHost.getId());
                            picker.setAllowregister(remoteHost.isAllowregister());
                            remoteHostPickers.add(picker);
                        }
                        if (BuildConfig.DEBUG) {
                            final RemoteHostPicker picker = new RemoteHostPicker();
                            picker.setHost("http://192.168.1.100:8080");
                            picker.setName("线下(DEBUG模式显示)");
                            picker.setId(501L);
                            picker.setAllowregister(true);
                            remoteHostPickers.add(picker);
                        }
                        if (!isFinishing()) {
                            showChooseSchoolDialog(remoteHostPickers);
                        }
                    }else{
                        ToastUtils.warning("获取学校域名列表失败");
                    }
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<List<RemoteHost>>> call, Throwable t) {
                super.onFailure(call, t);
                List<RemoteHostPicker> remoteHostPickers = new ArrayList<>();
                if (BuildConfig.DEBUG) {
                    final RemoteHostPicker picker = new RemoteHostPicker();
                    picker.setHost("http://192.168.1.100:8080");
                    picker.setName("线下(DEBUG模式显示)");
                    picker.setId(501L);
                    picker.setAllowregister(true);
                    remoteHostPickers.add(0,picker);
                }
                if (!isFinishing()) {
                    showChooseSchoolDialog(remoteHostPickers);
                }
            }
        });
    }

    private void updateRemoteHost() {
        remoteHostCall = systemApi.remoteHost();
        remoteHostCall.enqueue(new ServerCallback<List<RemoteHost>>() {
            @Override
            public void onResponse(boolean success, ServerResponse<List<RemoteHost>> response) {
                if (success) {
                    final List<RemoteHost> body = response.getBody();
                    // 比对remote host
                    RemoteHostPicker currentRemoteHost = RemoteHostUtil.getCurrentRemoteHost();
                    if (currentRemoteHost != null && body != null && !body.isEmpty()) {
                        for (RemoteHost remoteHost : body) {
                            if (remoteHost != null) {
                                if (currentRemoteHost.getName().equals(remoteHost.getName()) && ObjectUtils.equals(currentRemoteHost.getId(), remoteHost.getId())) {
                                    currentRemoteHost.setHost(remoteHost.getHost());
                                    RetrofitUrlManager.getInstance().setGlobalDomain(remoteHost.getHost());
                                    RemoteHostUtil.saveCurrentRemoteHost(currentRemoteHost);
                                    RetrofitUrlManager.getInstance().setGlobalDomain(currentRemoteHost.getHost());
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<List<RemoteHost>>> call, Throwable t) {
                super.onFailure(call, t);
            }
        });
    }


    private void showChooseSchoolDialog(final List<RemoteHostPicker> remoteHostPickers) {
        AndroidUtils.hideSoftInput(getWindow());
        if (!remoteHostPickers.isEmpty()) {
            final OptionsPickerView optionsPickerView = new OptionsPickerView.Builder(StudentIdLoginActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int i, int i1, int i2, View view) {
                    final RemoteHostPicker remoteHostPicker = remoteHostPickers.get(i);
                    tvChooseSchoolName.setText(remoteHostPicker.getName());
                    tvChooseSchoolName.setTag(remoteHostPicker.getId());
                    RetrofitUrlManager.getInstance().setGlobalDomain(remoteHostPicker.getHost());
                    RemoteHostUtil.saveCurrentRemoteHost(remoteHostPicker);
                }
            }).setTitleText("请选择学校").build();
            optionsPickerView.setPicker(remoteHostPickers);
            optionsPickerView.show();
        }else{
            ToastUtils.warning("没有获取到学校数据，请重试！");
        }
    }

    private void login() {
        if (tvChooseSchoolName.getTag() == null) {
            ToastUtils.info("请先选择要登录的学校");
            return;
        }
        if (InputUtils.validateInput(etName, "请输入用户名") && InputUtils.validateInput(etPassword, "请输入登录密码")) {
            final String userName = etName.getText().toString().trim();
            final String password = etPassword.getText().toString().trim();
            HashMap<String, String> params = new HashMap<>();
            params.put("loginStr", userName);
            params.put("password", password);
            params.put("universityId", String.valueOf(tvChooseSchoolName.getTag()));
            params.put("platform", "1");
            btnLogin.setText("登录中...");
            loginCall = ApiUtils.getApi(UserApi.class).login(params);
            loginCall.enqueue(new ServerCallback<UserInfo>(this, "登录中...") {
                @Override
                public void onResponse(boolean success, ServerResponse<UserInfo> response) {
                    if (success) {
                        PrefUtils.setExpiresLoginTime(System.currentTimeMillis());
                        UserInfo userInfo = response.getBody();
                        PrefUtils.setLastJobNumber(userName);
                        PrefUtils.setLastPassword(password);
                        initUserInfo(userInfo);
                    }else{
                        if (btnLogin != null) {
                            btnLogin.setText("登录");
                        }
                    }

                }

                @Override
                public void onFailure(Call<ServerResponse<UserInfo>> call, Throwable t) {
                    super.onFailure(call, t);
                    if (btnLogin != null) {
                        btnLogin.setText("登录");
                    }
                }
            });
        }
    }


    /**
     * 初始化用户信息，存储用户信息
     *
     * @param userInfo
     */
    private void initUserInfo(UserInfo userInfo) {
        UserUtils.setUserInfo(userInfo);
        if (userInfo.isBind()) {
            startActivity(new Intent(StudentIdLoginActivity.this, BindMobileActivity.class));
            if (btnLogin != null) {
                btnLogin.setText("登录");
            }
        } else {
            if (!UserUtils.checkIsStudent(this, userInfo)) {
                return;
            }
            UserUtils.setAccessToken(userInfo.getToken());
            UserInfoDao.saveUserInfo(userInfo);
            JPushAliasUtils.getInstance().setJPushAlias(this);
            EventBus.getDefault().post(new UpdateCourseEvent());
            startActivity(new Intent(StudentIdLoginActivity.this, MainActivity.class));
            ActivityStackManager.finish();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loginCall != null) {
            loginCall.cancel();
        }
        if (remoteHostCall != null) {
            remoteHostCall.cancel();
        }
    }
}
